<template>
  <input ref="uploadImgs" type="file" style="display: none" @change="sendImagesMessage()" single accept="image/*" />
</template>

<script setup>
import { ref } from "vue";
import { MESSAGE_TYPE } from "@/IM/constant";
import saveMsg from "../../utils/saveMsg.js";
const emit = defineEmits(["onStartLoading", "onLoadending"]);
const uploadImgs = ref(null);
const openChooseImages = () => {
  uploadImgs.value.click();
};
//发送图片
const sendImagesMessage = async () => {
  const file = {
    data: null, // file 对象。
    filename: "", //文件名称。
    filetype: "" //文件类型。
  };
  const url = window.URL || window.webkitURL;
  const img = new Image(); //手动创建一个Image对象
  const msgOptions = {
    file: file,
    onFileUploadError: () => {
      // 图片文件上传失败。
      console.log("onFileUploadError");
      emit("onLoadending");
    },
    onFileUploadProgress: e => {
      // 图片文件上传进度。
      console.log(e);
      emit("onStartLoading");
    },
    onFileUploadComplete: () => {
      // 上传成功。
      emit("onLoadending");
    }
  };
  //读取图片的宽高
  const imgFile = uploadImgs.value.files[0];
  file.data = imgFile;
  file.filename = imgFile.name;
  file.filetype = imgFile.type;
  img.src = url.createObjectURL(imgFile); //创建Image的对象的url
  img.onload = async () => {
    msgOptions.width = img.width;
    msgOptions.height = img.height;
    saveMsg(msgOptions, MESSAGE_TYPE.IMAGE);
  };
};
defineExpose({
  openChooseImages
});
</script>

<style lang="scss" scoped></style>
